package com.mine.yyb.modules.sys.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mine.yyb.common.utils.exception.MineErrorCode;
import com.mine.yyb.common.utils.exception.MineException;
import com.mine.yyb.common.utils.jdbc.MinePagination;
import com.mine.yyb.common.utils.json.MineJacksonkMapper;
import com.mine.yyb.common.utils.spring.MineSpringPropertyConfigurer;
import com.mine.yyb.common.web.YybBaseController;
import com.mine.yyb.modules.sys.bo.UserBO;
import com.mine.yyb.modules.sys.enums.SysCodeEnum;
import com.mine.yyb.modules.sys.enums.UserRoleEnum;
import com.mine.yyb.modules.sys.service.IUserService;
import com.mine.yyb.modules.sys.vo.UserVO;

/**
 * <pre>
 * <一句话功能简述>
 * 系统模块
 * <功能详细描述>
 * 包括注册 登录 校验等功能
 * </pre>
 * 
 * @author xuganhua
 * @version [版本号, 2015年12月21日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@RequestMapping(value = "/sys/user")
public class UserControl extends YybBaseController
{
    
    @Autowired
    private IUserService iUserService;
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 进入系统订单页面
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年5月21日]
     * @param request
     * @param response
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/initAccountPage")
    public String initAccountPage(HttpServletRequest request, HttpServletResponse response)
    {
        getResponseHeader(response);
        return "/html/account";
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 普通用户密码重置
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年1月21日]
     * @param request
     * @param userBO
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/pwdRecovery")
    public ResponseEntity<String> pwdRecovery(HttpServletRequest request, @ModelAttribute UserBO userBO)
    {
        // 响应码
        String retCode = null;
        try
        {
            logger.info(userBO.toString());
            
            // 判断邮箱是否为空
            if (StringUtils.isBlank(userBO.getEmail()))
            {
                throw new MineException(SysCodeEnum.ERROR_EMAIL_BLANK);
            }
            
            retCode = iUserService.pwdRecovery(userBO);
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
            retCode = e.getErrorCode().name();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            retCode = MineErrorCode.ERROR_INTERNAL.name();
        }
        return getResponseEntity(retCode);
    }
    
    /**
     * <一句话功能简述>
     * 
     * 删除用户
     *
     * <功能详细描述>
     * 
     * @param request
     * @param userBO
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/deleteUser")
    public ResponseEntity<String> deleteUser(HttpServletRequest request, @ModelAttribute UserBO userBO)
    {
        String retCode = null;
        try
        {
            logger.info(userBO.toString());
            
            // 判断用户内部ID是否为空
            if (StringUtils.isBlank(userBO.getInnerID()))
            {
                throw new MineException(SysCodeEnum.ERROR_INNERID_BLANK);
            }
            
            retCode = iUserService.deleteUser(userBO);
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
            retCode = e.getErrorCode().name();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            retCode = MineErrorCode.ERROR_INTERNAL.name();
        }
        return getResponseEntity(retCode);
    }
    
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 获得当前的用户信息
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2015年12月25日]
     * @param request
     * @param userBO
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/getUser")
    public ResponseEntity<String> getUser(HttpServletRequest request, @ModelAttribute UserBO userBO)
    {
        logger.info(userBO.toString());
        String retCode = MineErrorCode.SUCCESS.name();
        
        UserVO userVO = (UserVO)request.getSession(false).getAttribute("userToken");
        userVO.setPassword(null);
        
        return getResponseEntity(retCode, userVO);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 分页查询用户信息
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年1月4日]
     * @param request
     * @param userBO
     * @return
     * @throws MineException
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/queryUser")
    public ResponseEntity<String> queryUser(HttpServletRequest request, @ModelAttribute UserBO userBO)
        throws MineException
    {
        String retCode = null;
        MinePagination<UserVO> result = null;
        try
        {
            logger.info(userBO.toString());
            
            result = iUserService.queryUserList(userBO);
            retCode = MineErrorCode.SUCCESS.name();
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
            retCode = e.getErrorCode().name();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            retCode = MineErrorCode.ERROR_INTERNAL.name();
        }
        return getResponseEntity(retCode, result);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 退出系统
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年1月5日]
     * @param request
     * @param userBO
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/logout")
    public ResponseEntity<String> logout(HttpServletRequest request, @ModelAttribute UserBO userBO)
    {
        String retCode = null;
        try
        {
            logger.info(userBO.toString());
            
            request.getSession().removeAttribute("userToken");
            
            retCode = MineErrorCode.SUCCESS.name();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            retCode = MineErrorCode.ERROR_INTERNAL.name();
        }
        return getResponseEntity(retCode);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 下载系统使用说明文档
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年1月13日]
     * @param request
     * @param response
     * @throws MineException
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/download")
    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws MineException
    {
        try
        {
            // 文件名称
            String filename = "shiyongshuoming.docx";
            String encodefilename = URLEncoder.encode(filename, "UTF-8");
            
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + encodefilename);
            
            InputStream is =
                new FileInputStream(new File(System.getProperty("catalina.home") + "/conf/yyb/" + filename));
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
            os.close();
            is.close();
        }
        catch (Exception e)
        {
            throw new MineException(MineErrorCode.ERROR_INTERNAL);
        }
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 更新用户的支付宝信息
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年1月19日]
     * @param request
     * @param userBO
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/updateUserPay")
    public ResponseEntity<String> updateUserPay(HttpServletRequest request, @ModelAttribute UserBO userBO)
    {
        // 响应码
        String retCode = null;
        try
        {
            logger.info(userBO.toString());
            
            // 判断内部ID是否为空
            if (StringUtils.isBlank(userBO.getInnerID()))
            {
                throw new MineException(SysCodeEnum.ERROR_INNERID_BLANK);
            }
            
            retCode = iUserService.updateUserPay(userBO);
            
            UserVO userVO = (UserVO)request.getSession().getAttribute("userToken");
            if (userVO != null)
            {
                userBO.setUsername(userVO.getUsername());
                userBO.setRole(UserRoleEnum.USER_NORMAL_ROLE.getRole());
                userVO = iUserService.queryTheUser(userBO);
                request.getSession().setAttribute("userToken", userVO);
            }
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
            retCode = e.getErrorCode().name();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            retCode = MineErrorCode.ERROR_INTERNAL.name();
        }
        return getResponseEntity(retCode);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 更新用户的qq信息
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年5月6日]
     * @param request
     * @param userBO
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/updateUserQQ")
    public ResponseEntity<String> updateUserQQ(HttpServletRequest request, @ModelAttribute UserBO userBO)
    {
        // 响应码
        String retCode = null;
        try
        {
            logger.info(userBO.toString());
            
            // 判断内部ID是否为空
            if (StringUtils.isBlank(userBO.getInnerID()))
            {
                throw new MineException(SysCodeEnum.ERROR_INNERID_BLANK);
            }
            
            retCode = iUserService.updateUserQQ(userBO);
            
            UserVO userVO = (UserVO)request.getSession().getAttribute("userToken");
            if (userVO != null)
            {
                userBO.setUsername(userVO.getUsername());
                userBO.setRole(UserRoleEnum.USER_NORMAL_ROLE.getRole());
                userVO = iUserService.queryTheUser(userBO);
                request.getSession().setAttribute("userToken", userVO);
            }
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
            retCode = e.getErrorCode().name();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            retCode = MineErrorCode.ERROR_INTERNAL.name();
        }
        return getResponseEntity(retCode);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 检查支付宝账号是否已经存在
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年3月14日]
     * @param request
     * @param userBO
     * @return
     * @throws MineException
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/checkPayAccount")
    public ResponseEntity<String> checkPayAccount(HttpServletRequest request, @ModelAttribute UserBO userBO)
        throws MineException
    {
        boolean result = true;// 表示支付宝账号已经存在
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", result);
        try
        {
            logger.info(userBO.toString());
            
            // 判断邮箱是否为空
            if (StringUtils.isBlank(userBO.getPayAccount()))
            {
                throw new MineException(SysCodeEnum.ERROR_PAYACCOUNT_BLANK);
            }
            
            result = iUserService.isPayAccountExist(userBO);
            map.put("valid", !result);
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<String>(MineJacksonkMapper.convertObjectToString(map), responseHeaders,
            HttpStatus.OK);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 获得推广链接根地址
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年3月14日]
     * @param request
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/getInviteRegisterUrl")
    public ResponseEntity<String> getInviteRegisterUrl(HttpServletRequest request)
    {
        // 响应码
        String retCode = null;
        // 推广注册根地址
        String registerUrl = null;
        try
        {
            logger.info("getInviteRegisterUrl");
            
            registerUrl = MineSpringPropertyConfigurer.getProperty("invite.register").toString();
            retCode = MineErrorCode.SUCCESS.name();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            retCode = MineErrorCode.ERROR_INTERNAL.name();
        }
        return getResponseEntity(retCode, registerUrl);
    }
}
